#include <iostream>
#include <pthread.h>
using namespace std;


class Singleton{
private:
    int _ix;
    int _iy;
    static Singleton * _pInstance;
    friend class AutoRelease;

private:
    Singleton() = default;//C++11
    Singleton(int x,int y): _ix(x), _iy(y){
        cout << "Singleton(int,int)" << endl;
    }
    ~Singleton(){
        cout << "~Singleton()" << endl;
    }
    Singleton(const Singleton & rhs) = delete;
    Singleton & operator=(const Singleton & rhs) = delete;

public:
    static Singleton * getInstance(){
        if(nullptr == _pInstance){
            _pInstance = new Singleton(0,0);
        }
        return _pInstance;
    }
    void init(int x,int y){
        _ix = x;
        _iy = y;
    }
    void print(){
        cout << "(" << this->_ix
             << "," << this->_iy
             << ")" << endl;
    }
};
Singleton * Singleton::_pInstance = nullptr;



class AutoRelease{
private:
    Singleton* _singleton;
public:
    AutoRelease(Singleton* singleton){
        _singleton = singleton;
        printf("AutoRelease()");
    }
    ~AutoRelease(){
        if(_singleton){
            delete _singleton;
            _singleton = nullptr;
        }
    }
};


void test0(){
    AutoRelease autoRelease(Singleton::getInstance());
    /**
     * 可以将destroy去掉，避免double free
     */
    Singleton::getInstance()->print();
    Singleton::getInstance()->init(7, 8);
    Singleton::getInstance()->print();


    /**
     * 这个需要人为避免
     */
//    AutoRelease autoRelease1(Singleton::getInstance());
}

int main(void) {
    test0();
    return 0;
}
